import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATE_FORMAT} from '../constants';
import {approveApplyReport, getDetail} from './api';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {partClaimCode, partClaimReasonStatus, partClaimResult, partClaimType, currency, partPaymentMethod} from '../Enum';
import {injectIntl, language} from './intl';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
const FormItem = Form.Item;

const partClaimCodesToList = partClaimCode.toList(language);
const partClaimResultToList = partClaimResult.toList(language);
class ApprovePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        data: {},
        details: []
    }
    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details,
                    });
                else
                    this.setState({loading: false});
            });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const details = this.state.details;
        const isValid = newOrUpdateOrderValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            receivingDealerName: data.receivingDealerName,
            address: data.address,
            contactNumber: data.contactNumber,
            destination: data.destination,
            rowVersion: data.rowVersion,
            details: details.map(v => ({
                id: v.id,
                partClaimCode: v.partClaimCode,
                result: v.result,
            })),
        };
        this.setState({loading: true});
        approveApplyReport(this.props.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onUpdateClaimCode = (partClaimCode, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    partClaimCode,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    onUpdateResult = (result, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    result,
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, isValidate, loading} = this.state;
        const {isDealerUser} = this.props;
        const columns = [{
            title: formatMessage({
                id: 'approvePanel.column.packingListCode',
                defaultMessage: '箱单号'
            }),
            dataIndex: 'packingListCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.partSaleOrderCode',
                defaultMessage: '备件销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.partName',
                defaultMessage: '备件中文名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.claimAmount',
                defaultMessage: '索赔数量'
            }),
            dataIndex: 'claimAmount',
        }, {
            title: formatMessage({
                id: 'approvePanel.column.price',
                defaultMessage: '索赔单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.claimFee',
                defaultMessage: '索赔金额'
            }),
            dataIndex: 'claimFee',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'approvePanel.column.claimReason',
                defaultMessage: '索赔原因'
            }),
            dataIndex: 'claimReason',
            render: text => conventEnumValueToString(partClaimReasonStatus, text)
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'approvePanel.column.partClaimCode',
                defaultMessage: '索赔代码'
            })}</span>
            ),
            dataIndex: 'partClaimCode',
            render: (text, record) => (<FormItem>
                <WrappedSelect
                    id={record.id}
                    options={partClaimCodesToList}
                    value={text}
                    onChange={this.onUpdateClaimCode} />
            </FormItem>)
        }, {
            title: (<span className="ant-form-item-required">{formatMessage({
                id: 'approvePanel.column.result',
                defaultMessage: '结果'
            })}</span>
            ),
            dataIndex: 'result',
            render: (text, record) => (<FormItem>
                <WrappedSelect
                    id={record.id}
                    options={partClaimResultToList}
                    value={text}
                    onChange={this.onUpdateResult} />
            </FormItem>)
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'approvePanel.column.common',
                        defaultMessage: '订单信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.code}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item}>
                                        ({data.brandCode}){data.brandName}
                                    </FormItem>
                                </Col>
                                { !isDealerUser && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.dealerCode',
                                        defaultMessage: '总代编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.dealerCode}
                                    </FormItem>
                                </Col>}
                                { !isDealerUser && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.dealerName',
                                        defaultMessage: '总代名称'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.dealerName}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.createTime',
                                        defaultMessage: '提报日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.createTime, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.claimCode',
                                        defaultMessage: '备件索赔单编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.claimCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.invoiceCode',
                                        defaultMessage: '发票号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.invoiceCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.invoicedDate',
                                        defaultMessage: '开票日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.invoicedDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.claimType',
                                        defaultMessage: '索赔类型'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(partClaimType, data.claimType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.receiptDate',
                                        defaultMessage: '收货日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.receiptDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.currency',
                                        defaultMessage: '币种'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.paymentMethod',
                                        defaultMessage: '赔付方式'
                                    })}{...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(partPaymentMethod, data.paymentMethod)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.shipmentDate',
                                        defaultMessage: '出运日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.shipmentDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.actualArrivalDate',
                                        defaultMessage: '到达日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.actualArrivalDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.claimCreateDate',
                                        defaultMessage: '索赔申请接收日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.claimCreateDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.claimAmount',
                                        defaultMessage: '索赔总数量'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.claimAmount}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.claimFee',
                                        defaultMessage: '索赔总金额'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatAmount(data.claimFee)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.receivingDealerName',
                                        defaultMessage: '收货方'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.receivingDealerName ? 'error' : null} required>
                                        <TextInput
                                            name="receivingDealerName"
                                            value={data.receivingDealerName}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.address',
                                        defaultMessage: '地址'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.address ? 'error' : null} required>
                                        <TextInput
                                            name="address"
                                            value={data.address}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.contactNumber',
                                        defaultMessage: '联系电话'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.contactNumber ? 'error' : null} required>
                                        <TextInput
                                            name="contactNumber"
                                            value={data.contactNumber}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'approvePanel.operation.destination',
                                        defaultMessage: '目的地'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.destination ? 'error' : null} required>
                                        <TextInput
                                            name="destination"
                                            value={data.destination}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'approvePanel.operation.detail',
                            defaultMessage: '订单清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'approvePanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

ApprovePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch
} from './actions';
const mapStateToProps = state => ({
    isDealerUser: state.getIn((['page', 'domainData', 'init', 'isDealerUser'])),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ApprovePanel));
